package com.bigfish.gbs.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Joycessh
 * @Description 处理文件上传
 * @Date 12/22/18 3:22 PM
 */
public class FileUploadUtil {

    public static String fileUpload(MultipartFile imageFile, HttpServletRequest request) throws IOException {

        String fileName = "";
        String path = "";
        String fileUploadPath = "/home/joycessh/workspaces/IdeaProjects/images/ssm-gbs/goods/";

        if (!imageFile.isEmpty()) {
            String originalFilename = imageFile.getOriginalFilename(); // 获取上传的文件名
            String suffix = originalFilename.substring(originalFilename.indexOf(".")); // 获取文件后缀

            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateStr = sdf.format(now);
//            DateFormat dateFormat = DateFormat.getDateInstance();
//            String timeStr = dateFormat.format(now).replace("-", "");

            String randomStr = CommonUtil.getMethodRandow(6);

            fileName = dateStr + randomStr + suffix;   // 生成新的文件名

            imageFile.transferTo(new File(fileUploadPath + fileName));
        }
        path = "/image/goods/" + fileName;
        return path;
    }

}
